package com.github.jlmd.animatedcircleloadingview.component;

import com.github.jlmd.animatedcircleloadingview.animator.AnimationState;
import com.github.jlmd.animatedcircleloadingview.animator.MyStateChange;
import com.github.jlmd.animatedcircleloadingview.animator.MyValueAnimator;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.render.Arc;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;

/**
 * @author jlmd
 */
public class MainCircleView extends ComponentViewAnimation implements Component.DrawTask {
    boolean isRest = false;
    private Paint paint;
    private RectFloat oval;
    private int arcFillAngle = 0;
    private int arcStartAngle = 0;

    public MainCircleView(Context context, int parentWidth, Color mainColor, Color secondaryColor) {
        super(context, parentWidth, mainColor, secondaryColor);
        init();
        addDrawTask(this);
    }

    private void init() {
        initPaint();
        initOval();
    }

    private void initPaint() {
        paint = new Paint();
        paint.setColor(mainColor);
        paint.setStrokeWidth(strokeWidth);
        paint.setStyle(Paint.Style.FILLANDSTROKE_STYLE);
        paint.setAntiAlias(true);
    }

    private void initOval() {
        float padding = paint.getStrokeWidth() / 2;
        oval = new RectFloat(parentCenter - circleRadius, padding, parentCenter + circleRadius, circleRadius * 2);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (!isRest)
            drawArcs(canvas);
    }

    private void drawArcs(Canvas canvas) {
        canvas.drawArc(oval, new Arc(arcStartAngle, arcFillAngle, false), paint);
    }

    public void startFillCircleAnimation() {
        MyValueAnimator valueAnimator = new MyValueAnimator();
        valueAnimator.setFloat(90, 360);
        valueAnimator.setDuration(800);
        valueAnimator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float value) {
                arcStartAngle = (int) value;
                arcFillAngle = (90 - arcStartAngle) * 2;
                isRest = false;
                invalidate();
            }
        });
        valueAnimator.setStateChangedListener(new MyStateChange() {
            @Override
            public void onStart(Animator animator) {
                isRest = false;
            }

            @Override
            public void onEnd(Animator animator) {
                setState(AnimationState.MAIN_CIRCLE_FILLED_TOP);

            }
        });
        valueAnimator.start();
    }

    public void reset() {
        initOval();
        isRest = true;
        invalidate();
    }
}
